function [ EC ] = APEextractspectrum( datasetname, framenumber )
%[ EC ] = APEextractspectrum( datasetname, framenumber )
%
%   Extracts a single Spectrum from a Kinetic time series and saves it to a
%   new .mat file, conserving all additional information present.
%
% INPUT     datasetname     :   File name of source 
%           framenumber     :   Index of the spectrum to extract
%
% OUTPUT            EC      :   Error Code. (0=success, 1=error)

% DEPENDENCIES              - 

%  (c) F. Dworkowski, 2011-13
%      Version 1.1, 2013-12-19
%      Version 1.0, 2011-08-05

%% ===== INITALIZE  =====
if nargin<1,
    help APEextractspectrum
    EC = 1;
    return
end

%% =====   CONFIG   =====
EC=0;

%% =====    CODE    =====
try load(datasetname)
catch ME
  errordlg('ERROR: file not found in "APEextractspectrum"!')
  return
end

% --- Ask for index if not given in prompt ---
if nargin<2
    prompt = ['Which spectra should be extracted? (1:',...
                num2str(length(datay(1,:))),')'];
	dlg_title = 'Which Spectra to Use?';
    num_lines = 1;
    def = '1';
    answer = inputdlg(prompt,dlg_title,num_lines);
    framenumber = str2num(cell2mat(answer));
end
    

newset = load(datasetname); % copy all information to new set before reduction

framenumber = round(framenumber);       % avoid non-integer input
if framenumber > length(datay(1,:))     % check if index is available
    errordlg('ERROR: Please give correct Index for extraction!')
    EC = 1;
    return
end

newset.datay = datay(:,framenumber);

% --- check for ALS corrected Data and process if applicable ---
if exist('ALSdatay','var')
    disp('ALS in da house')
    newset.ALSdatay = ALSdatay(:,framenumber);
    newset.ALSbasey = ALSbasey(:,framenumber);
    newset.ALSres   = ALSres(:,framenumber);
else
    disp('No ALS. Soooo sad!')
end
% --- check for Dose Data and process if applicable ---
if exist('dose','var')
    disp('Dose received, homes')
    newset.dose = dose(:,framenumber);
else
    disp('No dose data. Soooo sad!')
end

if length(framenumber) > 1
    outfilename = [datasetname,'_spec-',num2str(framenumber(1)),'-', ...
                            num2str(framenumber(length(framenumber)))];
else
    outfilename = [datasetname,'_spec-',num2str(framenumber)];
end
save(outfilename, '-struct', 'newset');

end % =====================================================================

